# -*-coding:UTF-8-*-
import requests
import json
from openpyxl import Workbook


def GetWriteData(url, num, fname):
    wb = Workbook()
    ws = wb.active
    ws.append(['片名', '豆瓣评分', '主演', '影片封面'])
    i = 0
    while i < num:
        html = requests.get(url + str(i))
        if '异常请求' in html.text:
            print('请求过于频繁，请稍后再试！')
            break
        text = json.loads(html.text[8:-1])
        i += 20
        for j in text:
            ws.append([j['title'], j['rate'], ''.join(j['casts']), j['cover']])
            wb.save(fname)
        print('任务结束。')


if __name__ == '__main__':
    fname = 'db.xlsx'
    url = 'https://movie.douban.com/j/new_search_subjects?sort=S&range=0,100&tags=电影&start='
    print('开始获取,请稍候...')
    GetWriteData(url, 200, fname)
